import 'package:ble_file_transfer/consts.dart';
import 'package:ble_file_transfer/util/my_log.dart';
import 'package:ble_file_transfer/util/permission_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String tag = "_HomePageState";
  bool debug = true;

  @override
  void initState() {
    PermissionUtil.requestBleAndLocationPermission()
        .then((value) => searchDevice());
    super.initState();
  }

  @override
  void dispose() {
    FlutterBluePlus.stopScan();
    super.dispose();
  }

  AppBar _buildAppBar() => AppBar(
        title: const Text("BLE File Transfer"),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      );

  Widget _buildBody() => Container(
        child: const Row(
          children: [
            SizedBox(
              width: 10,
              height: 10,
              child: CircularProgressIndicator(
                strokeWidth: 1,
              ),
            ),
            SizedBox(
              width: 8,
            ),
            Text("搜索设备中..."),
          ],
        ),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: _buildBody(),
    );
  }

  void searchDevice() {
    FlutterBluePlus.scanResults.listen((scanResults) {
      debugLog("发现一个设备：$scanResults");
    });

    FlutterBluePlus.startScan(
      withServices: [Guid(Consts.uuid)],
    );
  }

  void debugLog(String msg) {
    if (debug) MyLog.i(tag, msg);
  }
}
